package com.ybc.chinese.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.ybc.chinese.R;
import com.ybc.chinese.activity.DetailActivity;
import com.ybc.chinese.bean.Idiom;
import com.ybc.chinese.utils.Contants;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>成语<p/>
 * Created by Yubch on 17/2/16.
 */
public class IdiomAdapter extends BaseAdapter {
    private Context mCtx;
    private List<Idiom> datas;

    public IdiomAdapter(Context ctx) {
        mCtx = ctx;
        datas = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int i) {
        return datas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        final Idiom idiom = datas.get(position);
        if(convertView == null) {
            convertView = LayoutInflater.from(mCtx).inflate(R.layout.item_layout, null);
            holder = new Holder();
            holder.tvCircle = (TextView) convertView.findViewById(R.id.tv_circle);
            holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }
        if(idiom != null) {
            holder.tvCircle.setText(idiom.getTitle().substring(0, 1));
            holder.tvCircle.setBackgroundResource(Contants.CIRCLE_BG[position % Contants.CIRCLE_BG.length]);
            holder.tvTitle.setText(idiom.getTitle());
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DetailActivity.newIntent(mCtx, idiom.getTitle());
                }
            });
        }
        return convertView;
    }

    class Holder {
        TextView tvCircle;
        TextView tvTitle;
    }

    public void setData(List<Idiom> idioms, boolean isMore) {
        if(!isMore && getCount() > 0) {
            datas.clear();
        }
        datas.addAll(idioms);
        notifyDataSetChanged();
    }
}
